'''
Copyright (C) <2011> by Kevin Klein

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
'''

import sys

class Handler(object):

    '''
    this is the base class for rpc services
    '''

    def __init__(self, name='', debug=True):
        self.funcs = {}
        self.name = ''
        self.debug = debug
        
    def register_function(self, func, name=''):
        if not name:
            name = func.__name__
        self.funcs[name] = func
        
    def remove_function(self, name):
        del self.funcs[name]
        
    def function(self, arg):
        if callable(arg):
            self.register_function(arg)
            return arg
        else:
            def inner(func):
                name = arg
                self.register_function(func, name=name)
                return func
            return inner
    
    def generate_response(self, args):
        raise NotImplemented()
        
    def parse_request(self, data):
        raise NotImplemented()
    
    def render_error(self, name, msg):
        raise NotImplemented()
        
    def validate(self, request):
        raise NotImplemented()
    
    def handle_call(self, data):
        data = data.decode('utf-8')
        ok, name, msg = self.validate(data)
        if not ok:
            return self.render_error(name, msg)
            
        method, params = self.parse_request(data)
        try:
            ret = self.funcs[method](*params)
        except Exception:
            err = sys.exc_info()[1]
            if self.debug: 
                return self.render_error(err.__class__.__name__, err.message)
            else:
                return self.render_error('internal error', 'an internal error occured, activate debug to see the message')
        
        return self.generate_response(ret)
        
